package 
{
  import flash.display.MovieClip;
  import flash.events.Event;
  import flash.media.Sound;
  import flash.utils.getDefinitionByName;
  
  /**
   * ...
   * @author ivan
   */
  public class RandomSound extends MovieClip 
  {
    
    [Inspectable(defaultValue="")]
    public function get sounds():Array { return _sounds; }
    public function set sounds(value:Array):void { _sounds = value; }
    
    private var _sounds:Array;
    
    public function RandomSound()
    {
      addEventListener(Event.EXIT_FRAME, onExitFrame);
    }
    
    private function onExitFrame(e:Event):void
    {
      removeEventListener(Event.EXIT_FRAME, onExitFrame);
      
      if (_sounds.length == 0)
      {
        trace("Error: No sounds selected.");
        return;
      }
      
      var idx:int = Math.random() * _sounds.length;
      
      trace("Creating sound '" + _sounds[idx] + "'.");      
      var soundClass:Class = getDefinitionByName(_sounds[idx]) as Class;
      
      if (!soundClass)
      {
        trace("Error: '" + _sounds[idx] + "' not found.");
        return;
      }
      
      var sound:Sound = new soundClass();
      
      if (!sound)
      {
        trace("Error: '" + _sounds[idx] + "' is not a sound.");
        return;
      }
      
      trace("playing sound '" + _sounds[idx] + "'.");
      sound.play();
    }
  }
  
}